package hqb.dev.webdeploy.flow;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.Charset;

/**
 * 命令行执行步骤
 *
 * @author HQB--2024-04-22
 **/
@Slf4j
public class FlowStepCommand extends FlowStep {

    private final FlowStepCommandEnv env;
    private final File dir;
    private final String command;
    private String encoding = "UTF-8";
    private long timeout = 10000;

    public FlowStepCommand(String name, String desc, JSONObject y) {
        super(name, desc);
        this.env = new FlowStepCommandEnv(y.getJSONObject("env"));
        this.dir = new File(y.getStr("path")).getAbsoluteFile();
        this.command = y.getStr("command");
        String enc = y.getStr("encoding");
        if (StrUtil.isNotEmpty(enc)) {
            this.encoding = enc;
        }
        Long timeout = y.getLong("timeout");
        if (timeout != null) {
            this.timeout = timeout;
        }
    }

    @Override
    public void execute() {
        Thread thread = new Thread(() -> {
            String[] envs = env.getEnvs();
            Process exec = RuntimeUtil.exec(envs, dir, command);
            Charset charset = Charset.forName(encoding);
            String result = RuntimeUtil.getResult(exec, charset);
            if (StrUtil.isNotEmpty(result)) {
                log.info("执行结果:{}", result);
            }
        });
        thread.start();
        while (thread.isAlive() && timeout > 0) {
            ThreadUtil.sleep(1000);
            timeout -= 1000;
        }
        thread.interrupt();
    }
}
